package com.newy.core.hibernate;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.criterion.CriteriaQuery;
import org.hibernate.criterion.Order;

/**
 * 自定义排序类，解决mysql对中文字段的按拼音排序的问题
 * @author linzongxue
 *
 */
public class CnOrder extends Order{
	private static final long serialVersionUID = 6143429156582718563L;
	private String propertyName;
	private boolean asc;
	protected CnOrder (String propertyName, boolean asc){
		super(propertyName, asc);
		this.asc = asc;
		this.propertyName = propertyName;
	}
	
	public String toSqlString(Criteria criteria, CriteriaQuery query) throws HibernateException{
		String dialect = query.getFactory().getDialect().getClass().getName();
		String[] cols = query.getColumnsUsingProjection(criteria, propertyName);
		if (dialect.toLowerCase().contains("mysql")){
			return "convert(" + cols[0] + " using gbk)" + (this.asc ? " asc" : " desc");
		}
		return cols[0] + (this.asc ? " asc" : " desc");
	}
	
	public static CnOrder asc(String propertyName){
		return new CnOrder(propertyName, true);
	}
	
	public static CnOrder desc(String propertyName){
		return new CnOrder(propertyName, false);
	}
}
